package com.jiuyou.storeController.staff;/**
 * @Title:staffLoginController
 * @ClassName: ruoyi
 * @Description: TODO
 * @author: java
 * @time: 2024/3/7 16:10
 */

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.domain.model.LoginStoreUser;
import com.ruoyi.common.core.domain.model.StaffLoginBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.*;
import com.ruoyi.staff.service.impl.StaffServiceImpl;
import com.ruoyi.storeUser.service.impl.StoreUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: staffLoginController
 * @Description: TODO
 * @author: java
 * @time: 2024/3/7 16:10
 * 小程序员工登陆
 */
@RestController
public class staffLoginController {

    @Autowired
    private StaffServiceImpl staffService;
    @Autowired
    private StoreUserTokenService storeUserTokenService;
    @Autowired
    private StoreUserServiceImpl storeUserService;
    @PostMapping("/staffLogin")
    public AjaxResult staffLogin(@RequestBody StaffLoginBody staffLoginBody) {
        System.out.println(staffLoginBody.getPhone());
        String phone = staffLoginBody.getPhone();
        StoreUser staff=storeUserService.selectStoreUserByOpenIdOrPhone(null,phone);
        if (StringUtils.isNull(staff)) {
            throw new ServiceException("用户" + phone + " 不存在");
        } else if (staff.getDelState().equals("Y")) {
            throw new ServiceException("账号：" + phone + " 已被删除");
        } else if (staff.getState().equals("N")) {
            throw new ServiceException("账号：" + phone + " 已停用");
        } else {
            String encodedpassword = staffService.selectStaffByPhone(staffLoginBody.getPhone()).getPassword();
            if (SecurityUtils.matchesPassword(staffLoginBody.getPassword(), encodedpassword)) {
                AjaxResult ajax = AjaxResult.success();
                String token = storeUserTokenService.createToken(new LoginStoreUser(staff));
                ajax.put(Constants.TOKEN, token);
                return ajax;
            } else
                throw new ServiceException("账号与密码不匹配");
        }
    }
}
